package com.bmft.hello.test;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.bmft.hello.domain.User;
import com.bmft.hello.util.IndexConst;
import org.apache.lucene.util.QueryBuilder;
import org.assertj.core.data.Index;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.admin.indices.open.OpenIndexRequest;
import org.elasticsearch.action.admin.indices.open.OpenIndexResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.support.ActiveShardCount;
import org.elasticsearch.action.support.IndicesOptions;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.Cancellable;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.FetchSourceContext;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import javax.swing.*;
import java.io.IOException;
import java.util.Map;

/**
 * API的基本使用02
 *
 * @author Jarvan
 * @version 1.0
 * @create 2020/11/4 19:34
 */
@SpringBootTest
@RunWith(SpringRunner.class)
public class APIUseTest02 {
    @Autowired
    @Qualifier("restHighLevelClient")
    private RestHighLevelClient restHighLevelClient;

    /**
     * 创建索引
     *
     * @throws IOException
     */
    @Test
    public void testCreateIndex() throws IOException {
        CreateIndexRequest test01 = new CreateIndexRequest("test01");
        CreateIndexResponse createIndexResponse = restHighLevelClient
                .indices()
                .create(test01, RequestOptions.DEFAULT);
        System.out.println(createIndexResponse.isAcknowledged());
    }


    /**
     * Test whether index exist or not
     */
    @Test
    public void existIndex() throws IOException {
        GetIndexRequest getIndexRequest = new GetIndexRequest("test01");
        boolean exists = restHighLevelClient
                .indices().
                        exists(getIndexRequest, RequestOptions.DEFAULT);
        System.out.println(exists);
    }

    /**
     * Delete index if it exist
     */
    @Test
    public void deleteIndex() throws IOException {
        DeleteIndexRequest test01 = new DeleteIndexRequest("test01");
        AcknowledgedResponse delete = restHighLevelClient
                .indices()
                .delete(test01, RequestOptions.DEFAULT);
        System.out.println(delete.isAcknowledged());
    }

    /**
     * 添加文档记录
     */
    @Test
    public void addDoc() throws IOException {
        IndexRequest indexRequest = new IndexRequest("test01");
        User user = new User("张三老师1", 13);
        //给request配置source
        indexRequest.source(JSONArray.toJSONString(user), XContentType.JSON);
        //set timeout
        indexRequest.timeout("1s");
        //set id
        indexRequest.id("1");
        // 【发送request】
        IndexResponse index = restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
        System.out.println(index.getResult());

    }

    /**
     * doc id是否存在。
     */
    @Test
    public void searchDocTest() throws IOException {
        GetRequest getRequest = new GetRequest("test01", "1");
        //只是判断索引时是否存在不需要获取sources资源
        getRequest.fetchSourceContext(new FetchSourceContext(false));
        getRequest.storedFields("_none_");
        boolean exists = restHighLevelClient.exists(getRequest, RequestOptions.DEFAULT);
        System.out.println(exists);
    }

    /**
     * 通过id获取doc
     */
    @Test
    public void getDocByIdTest() throws IOException {
        GetRequest getRequest = new GetRequest(IndexConst.INDEX_CONST, "1");
        GetResponse documentFields = restHighLevelClient.get(getRequest, RequestOptions.DEFAULT);
        Map<String, Object> source = documentFields.getSource();
        source.forEach((field, value) -> {
            System.out.println("field=" + field);
            System.out.println("value=" + value);
        });
    }
    /**
     * 改 update Doc
     */

    @Test
    public void updateDocTest() throws IOException {
        UpdateRequest updateRequest = new UpdateRequest(IndexConst.INDEX_CONST, "n1j_lXUBUOCqpcF4ziQk");
        updateRequest.doc(JSON.toJSONString(new User("李四",14)),XContentType.JSON);
        updateRequest.timeout();
        UpdateResponse update = restHighLevelClient.update(updateRequest, RequestOptions.DEFAULT);
        System.out.println(update.status());
    }

    /**
     * 批量增，删，改，查.
     * 批量删除和修改只需要将add改为对应的的delete，update再修改部分地方即可。
     */

    @Test
    public void bulkAdd() throws IOException {
        BulkRequest bulkRequest = new BulkRequest();
        bulkRequest.timeout("2s");
        //填入数据
        for (int i = 0; i < 5; i++) {
            bulkRequest
                    .add(new IndexRequest(IndexConst.INDEX_CONST)
                    .source(JSON.toJSONString(new User("张三老师" + (i + 1), 13)), XContentType.JSON));
        }
        //发送请求
        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        System.out.println(bulk.status());
    }
    /**
     * 删 Doc
     */

    @Test
    public void deleteDocTest() throws IOException {
        DeleteRequest deleteRequest = new DeleteRequest();
        deleteRequest.id("1");
        deleteRequest.index(IndexConst.INDEX_CONST);
        DeleteResponse delete = restHighLevelClient.delete(deleteRequest, RequestOptions.DEFAULT);
        System.out.println(delete.status());
    }
    /**
     * 查 search 根据某个字段来搜索。
     * scroll 是什么？？问题？？？
     */
    @Test
    public void searchDocTest2() throws IOException {
        SearchRequest searchRequest = new SearchRequest(IndexConst.INDEX_CONST);
        //【重点】构建searchSourcesBuilder
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //构建查询 term
        // term 是包含查询
        searchSourceBuilder.query(QueryBuilders.termQuery("name","张三"));
        //翻页
        searchSourceBuilder.from(0);
        searchSourceBuilder.size(2);
        //timeout
        searchSourceBuilder.timeout();
        //【将builder放入request中】
        searchRequest.source(searchSourceBuilder);
        //【搜索】
        SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        System.out.println(response.status());
        for (SearchHit hit : response.getHits()) {
            System.out.println(hit);
        }

    }

}
